﻿using Bot.Salesforce.Extension;
using Bot.Salesforce.Model;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace Bot.Salesforce
{
    public class TokenService : ITokenService
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly SalesforceSetting _salesforceSetting;
        private readonly ILogger<TokenService> _logger;

        public TokenService(IHttpClientFactory httpClientFactory,
            IOptions<SalesforceSetting> salesforceSetting,
            ILogger<TokenService> logger)
        {
            _httpClientFactory = httpClientFactory;
            _salesforceSetting = salesforceSetting.Value;
            _logger = logger;
        }

        public async Task<string> GetAccessTokenAsync(string host, string refreshToken)
        {
            var url = "/services/oauth2/token";
            var input = JsonConvert.SerializeObject(new
            {
                host,
                refreshToken,
                _salesforceSetting.LiveChat_SalesforceConsummerKEY,
                _salesforceSetting.LiveChat_SalesforceConsummerSecret,
                url = Utils.ConnectUrl(host, url),
            });
            _logger.LogDebug($"GetAccessTokenAsync input:{input}");

            var request = Utils.BuildHttpRequestMessage(host, url, Enum.EnumHttpMethod.Post);
            request.AddForm(new List<KeyValuePair<string, string>>()
            {
                new KeyValuePair<string, string>("refresh_token", refreshToken),
                new KeyValuePair<string, string>("grant_type", "refresh_token"),
                new KeyValuePair<string, string>("client_id", _salesforceSetting.LiveChat_SalesforceConsummerKEY),
                new KeyValuePair<string, string>("client_secret", _salesforceSetting.LiveChat_SalesforceConsummerSecret),
            });
            var response = await _httpClientFactory.SendAsync(request);
            _logger.LogDebug($"GetAccessTokenAsync response:{response}");
            return JsonConvert.DeserializeObject<AccessTokenResponse>(response).access_token;
        }
    }
}
